/**
*@Author zhengwei
**/
package org.lanqiao.webfm.servlet;

import java.util.*;
import java.io.Serializable;
import java.sql.*;
import java.lang.reflect.*;

import javacommon.base.*;
import javacommon.ijdbc.*;
import javacommon.util.*;
import javacommon.web.page.*;
import javacommon.web.util.ServletRequestUtils;

import org.lanqiao.webfm.model.*;
import org.slf4j.*;
import org.lanqiao.webfm.service.*;
import org.lanqiao.webfm.sys.SysConfig;
import org.lxh.smart.SmartUpload;
import org.lxh.smart.SmartUploadException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.commons.beanutils.BeanUtils;

/**
 * Goods增删改查Servlet
 * 
 */
@WebServlet(urlPatterns = { "/Goods/*" }) 
public class GoodsServlet extends BaseServlet {
	private static final Logger LOGGER = LoggerFactory.getLogger(GoodsServlet.class);
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	private GoodsService goodsService = GoodsService.getInstance();
	private TypeService typeService = TypeService.getInstance();
	// 新增之前
	protected void doCreateInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException , SQLException{
		shareTypes(request);
	    request.getRequestDispatcher("/pages/Goods/create.jsp").forward(
				request, response);
	}
	//共享所有商品分类
    private void shareTypes(HttpServletRequest request) throws SQLException {
        request.setAttribute("types", typeService.findAll());
    }
	// 保存新增的对象
	protected void doSaveInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
	    saveOrupdate(Goods.class, request, response,"save");
	}
	// 查询出数据呈现在表单中供用户修改
	protected void doEditInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException , SQLException{
		String id = request.getParameter("id");
		Goods goods = goodsService.getById(id);
		request.setAttribute("model", goods);
		shareTypes(request);
		request.getRequestDispatcher("/pages/Goods/edit.jsp").forward(request,
				response);
	}
	// 执行更改
	protected void doUpdateInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException , SQLException{
		saveOrupdate(Goods.class, request, response,"update");
	}
	
	// 执行删除
	protected void doDeleteInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
		// 1.获取表单数据,也就是用户选择的所有的id
		String[] ids = request.getParameterValues("items");
		goodsService.removeByIds(ids);
		response.sendRedirect(request.getContextPath()+"/Goods/list.do");
	}
	
	//列表
	public void doListInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
		PageRequest<Goods> pageRequest = new Goods();
		//request price:5000 pageSize:10 pegeNumber:1  typeId:210-->pageRequest
		populateQuery(pageRequest, DEFAULT_SORT_COLUMNS, request);
		Page page = goodsService.findPage(pageRequest);
		//共享数据:${page.result}  共享了关于搜索的信息:${query.typeId}  共享分页信息:
		savePage(page, pageRequest, request);
		if (ServletRequestUtils.getBooleanParameter(request, "flag", false)) {
			request.getRequestDispatcher("/pagesf/Goods/list.jsp").forward(request, response);
		}else {
			request.getRequestDispatcher("/pages/Goods/list.jsp").forward(request, response);
		}
	}
	//展示
	protected void doShowInternal(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
		//如果是联合主键，这些代码需要修改
		String id = request.getParameter("id");
		Goods goods = goodsService.getById(id);
		request.setAttribute("model", goods);
		boolean flag = ServletRequestUtils.getBooleanParameter(request, "flag", false);
		if (flag) {
			request.getRequestDispatcher("/pagesf/Goods/show.jsp").forward(request,
					response);
		}else {
			request.getRequestDispatcher("/pages/Goods/show.jsp").forward(request,
					response);
		}
	}	
	
	protected void saveOrupdate(Class<Goods> clazz, HttpServletRequest request, HttpServletResponse response,String op)
			throws ServletException, IOException , SQLException{
		Goods goods = new Goods();
		try {
			SmartUpload smartUpload=new SmartUpload();
			//从request中拷贝属性，要求请求参数和Goods的属性一致
			String goodsIconPath = SysConfig.GOODS_ICON_PATH+UUID.randomUUID().toString()+"/";
			List<String> paths= super.upload(request, response, smartUpload,goodsIconPath);
			goods.setPicList(paths);
			Map<String, Object> params = ServletRequestUtils.getParametersStartingWith(smartUpload.getRequest(), "");
			BeanUtils.copyProperties(goods, params);//执行拷贝
			if(op.equals("save")){
				goodsService.save(goods);
				response.sendRedirect(request.getContextPath()+"/Goods/list.do");
			}
			if(op.equals("update")){
				goodsService.update(goods);
				response.sendRedirect(request.getContextPath()+"/Goods/show.do?id="+request.getParameter("id"));
			}
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException("beanUtils.copyProperties() error",e);
		} catch (InvocationTargetException e) {
			throw new IllegalArgumentException("beanUtils.copyProperties() error",e.getTargetException());
		} catch (SmartUploadException e) {
			throw new RuntimeException(e);
		}
	}
}
